﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Estimate.Common.DBFieldTypes;
using Estimate.Common.Repository;
using Estimate.Common.Entity;
using Estimate.Common.Estimate;
using Estimate.Common.Estimate.EstimateValue;
using Newtonsoft.Json;

namespace Estimate.Reports
{
    /// <summary>
    /// 预报员详细成绩
    /// </summary>
    public class IndividualReport
    {
        #region 变量与对象
        private FullInfoReport memberReportScore;// 得分对象
        private FullInfoReport standardReportScore;// 标准评分对象
        private string ForecasterNum = "";
        private string ForecasterStation = "";
        IndividualReportResult Result = new IndividualReportResult();//预报员详细成绩结果
 
        protected string _connectionString;
        ExecutionStatus exeStatus = null;//程序执行状态
        #endregion

        #region 构造函数
       
        /// <summary>
        /// 预报员详细成绩类构造函数
        /// </summary>
        /// <param name="forecaster">系统前端传递过来的预报员</param>
        /// <param name="connectionString"></param>
        /// <param name="tid">程序执行任务号</param>
        public IndividualReport(string forecaster, string connectionString, string tid)
        {
            //由于 58248 镇江站已经取消，使用的是58252. 但是预报数据中一直使用的是58248,所以将镇江站手动修正为58248
            forecaster = forecaster.Replace("58252", "58248");

            _connectionString = connectionString;

            if (tid != "") exeStatus = new ExecutionStatus(tid);

            string[] strs = forecaster.Replace("'", "").Split('_');
            ForecasterStation=strs[0];
            ForecasterNum = strs[1]; 
        }
        #endregion

        #region 初始化，检索、筛选预报员排班表
        /// <summary>
        /// 初始化，检索、筛选预报员排班表
        /// </summary>
        /// <param name="beginDate"></param>
        /// <param name="endDate"></param>
        /// <param name="clocks"></param>
        /// <param name="sendpoints"></param>
        protected void Initial(DateTime beginDate, DateTime endDate, ForeSendpointType[] sendpoints)
        {
            if (exeStatus != null) exeStatus.SetMessage("Initial", "正在准备...");

            #region 检索预报员对应的地区站点
            string areaStations = "";
            string areaStationName = "";
            StationMatchRepository stationMatchRepository = new StationMatchRepository(_connectionString);
            Dictionary<string, string> AreaStations = stationMatchRepository.GetAllNameStationDictionary(StationMatchStationsType.area, StationMatchExtralType.cz);
            foreach (KeyValuePair<string, string> station in AreaStations)
            {
                if (station.Value.Contains(ForecasterStation))
                {
                    areaStations = station.Value;
                    areaStationName = station.Key;
                    break;
                }
            }
            #endregion

            #region 检索出时间段内排班表记录
            SendpointToClock parser = new SendpointToClock();
            ForeClockType[] clocks = parser.GetClockArrayWithSendPointArray(sendpoints);
            ScheduleRepository scheduleRepository = new ScheduleRepository(_connectionString);
            ScheduleEntity[] Schedules = scheduleRepository.GetSchedulesWithDateRange(beginDate, endDate, clocks, sendpoints);
            #endregion

            #region 筛选出forecaster的排班表

            List<ScheduleEntity> IndividualSchedules = new List<ScheduleEntity>();

            foreach (ScheduleEntity schedule in Schedules)
            {
                //由于 58248 镇江站已经取消，使用的是58252. 但是预报数据中一直使用的是58248,所以将镇江站手动修正为58248
                if (schedule.Station == "58252")
                    schedule.Station = "58248";

                if (schedule.Station != ForecasterStation)
                    continue;

                foreach (string fnum in schedule.ForecastNumber.Split(','))
                {
                    if (fnum != ForecasterNum)
                        continue;
                    ScheduleEntity se = new ScheduleEntity();
                    se.Copy(schedule);
                    se.ForecastNumber = fnum;
                    se.Stations = areaStations;
                    se.StationName = areaStationName;
                    IndividualSchedules.Add(se);
                }


            }
            #endregion

            memberReportScore = new FullInfoReport(_connectionString, ForeRepositoryFactory.NormalCityForeRepository(_connectionString), IndividualSchedules);
            memberReportScore.CulculateAllResult = true;
            memberReportScore.CulculateDeviationResult = false;
            memberReportScore.ExeStatus = exeStatus;

            standardReportScore = new FullInfoReport(_connectionString, ForeRepositoryFactory.ZytCityForeRepository(_connectionString), IndividualSchedules);
            standardReportScore.CulculateAllResult = true;
            standardReportScore.CulculateDeviationResult = false;
            standardReportScore.ExeStatus = exeStatus;

            if (exeStatus != null) exeStatus.DeleteMessage("Initial");
        }
        #endregion

        #region  数据准备并计算

        public void PrepareData(DateTime beginDate, DateTime endDate,ForeSendpointType[] sendpoints, ForeSemiType semitype)
        {
            ForeSpanType[] waterSpans = new ForeSpanType[] { ForeSpanType.FD00_12, ForeSpanType.FD12_24, ForeSpanType.FD00_24, ForeSpanType.FD24_48, ForeSpanType.FD48_72 };
            ForeSpanType[] tempSpans = new ForeSpanType[] { ForeSpanType.FD00_24, ForeSpanType.FD24_48, ForeSpanType.FD48_72 };

            Initial(beginDate, endDate, sendpoints);


            try
            {
                if (exeStatus != null)
                {
                    exeStatus.TotalSteps = memberReportScore.GetExeStatusTotalSteps(beginDate, endDate, semitype, waterSpans, tempSpans) + standardReportScore.GetExeStatusTotalSteps(beginDate, endDate, semitype, waterSpans, tempSpans);
                    exeStatus.SetMessage("memberReportScore", "计算标准得分");
                }

                memberReportScore.PrepareData(beginDate, endDate, semitype, waterSpans, tempSpans, sendpoints);

                if (exeStatus != null)
                {
                    exeStatus.DeleteMessage("memberReportScore");
                    exeStatus.SetMessage("standardReportScore", "计算技巧值评分标准");
                }


                standardReportScore.PrepareData(beginDate, endDate, semitype, waterSpans, tempSpans, sendpoints);

                if (exeStatus != null) exeStatus.DeleteMessage("standardReportScore");

            }
            catch (Exception ex)
            {

                Result.success = false.ToString();
                Result.msg = ex.ToString();
                if (exeStatus != null)
                {
                    exeStatus.DeleteMessage("memberReportScore");
                    exeStatus.DeleteMessage("standardReportScore");
                    exeStatus.SetMessage("Error", "程序执行出错");
                }
            }

        }

        #endregion

        #region  获取预报员成绩字符串
        /// <summary>
        /// 获取预报员成绩字符串
        /// </summary>
        /// <returns></returns>
        public string GetReportDataString()
        {
            if (exeStatus != null) exeStatus.SetMessage("GetReportDataString", "获取计算结果");
            try
            {
                string key = "";
                if (memberReportScore.RecordCount != null)
                {
                    List<string> keys = memberReportScore.RecordCount.Keys.ToList<string>();
                    key= keys[0];
                }
                Result.result["data"] = memberReportScore.ToResult(standardReportScore, key);
            }
            catch (Exception ex)
            {

                Result.success = false.ToString();
                Result.msg = ex.ToString();
                if (exeStatus != null)
                    exeStatus.SetMessage("Error", "程序执行出错");

            }
            if (exeStatus != null)
            {
                exeStatus.DeleteMessage("GetReportDataString");
                exeStatus.SetMessage(true, "ExecutionEnd", "执行完毕");
            }

            return JsonConvert.SerializeObject(Result);
        }
        #endregion
    }

   #region 用于JSON序列化

    public class IndividualReportResult
    {
        public string success = true.ToString();
        public string msg = "";
        public Dictionary<string, object> result = new Dictionary<string, object>();

        public IndividualReportResult()
        {
            result.Add("data",new Dictionary<string, object>());
        }
    }

   #endregion
}
